package com.ruangong.GitClient.GiteeAPI;


import android.content.Context;
import android.content.Intent;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.ruangong.GitClient.app.GiteeFile.GiteeFileContentActivity;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class GiteeFile {
    /*
    {
        "type": "dir",
        "size": null,
        "name": "app",
        "path": "app",
        "sha": "8d512b9f9c6a57e71f3bd2d88d84b265f1d4dd7b",
        "url": "https://gitee.com/api/v5/repos/SilverXQ/ruan-gong-project/contents/app",
        "html_url": "https://gitee.com/SilverXQ/ruan-gong-project/blob/master/app",
        "download_url": "https://gitee.com/SilverXQ/ruan-gong-project/raw/master/app",
        "_links": {
            "self": "https://gitee.com/api/v5/repos/SilverXQ/ruan-gong-project/contents/app",
            "html": "https://gitee.com/SilverXQ/ruan-gong-project/blob/master/app"
        }
     */
    private String type;
    private String size;
    private String name;
    private String path;
    private String sha;
    private String url;
    private String html_url;
    private String download_url;
    private _links _links;

    public GiteeFile() {
    }

    public GiteeFile(String type, String size, String name, String path, String sha, String url, String html_url, String download_url, _links _links) {
        this.type = type;
        this.size = size;
        this.name = name;
        this.path = path;
        this.sha = sha;
        this.url = url;
        this.html_url = html_url;
        this.download_url = download_url;
        this._links = _links;
    }

    /**
     * 从 JSON 字符串中解析 GiteeFile 对象。
     * @param json JSON 字符串
     * @return GiteeFile 对象
     */
    public static GiteeFile fromJson(String json) {
        return new com.google.gson.Gson().fromJson(json, GiteeFile.class);
    }

    /**
     * 获取文件信息。
     * @return 文件信息
     */
    public String getFileInfo() {
//        return "Type: " + type + "\n" + "Size: " + size + "\n" + "Name: " + name + "\n" + "Path: " + path + "\n" + "Sha: " + sha + "\n" + "Url: " + url + "\n" + "Html_Url: " + html_url + "\n" + "Download_Url: " + download_url + "\n" + "_Links: " + _links;
        return "Type: "+type+" Size: "+size+" Name: "+name+" Path: "+path+" Sha: "+sha+" Url: "+url+" Html_Url: "+html_url+" Download_Url: "+download_url+" _Links: "+_links;
    }

    /**
     * 显示文件信息。
     */
    public void showFileInfo() {
        System.out.println(getFileInfo());
    }


    /**
     * 获取文件内容。
     * @return 文件内容
     */
    public String getFileContent() {
        if("file".equals(type)) {
            OkHttpClient client = new OkHttpClient();
            System.out.println(GiteeUser.accessToken);
            System.out.println(url);
            Request request = new Request.Builder()
                    .url(url)
                    .header("Authorization", "token " + GiteeUser.accessToken)
                    .build();


            try (Response response = client.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    JsonObject jsonObject = JsonParser.parseString(responseBody).getAsJsonObject(); // 解析 JSON 字符串为 JsonObject

                    // 安全地从 JsonObject 中获取 content 字符串
                    String encodedContent = jsonObject.has("content") ? jsonObject.get("content").getAsString() : null;

                    // 检查 encodedContent 是否为空
                    if (encodedContent != null && !encodedContent.isEmpty()) {
                        // 解码 Base64 编码的 content
//                    byte[] decodedBytes = Base64.getDecoder().decode(encodedContent);
//                    String decodedContent = new String(decodedBytes, StandardCharsets.UTF_8);
                        String decodedContent = new String(java.util.Base64.getDecoder().decode(encodedContent), StandardCharsets.UTF_8);
//                    String decodedContent = new String(android.util.Base64.decode(encodedContent, Base64.DEFAULT), StandardCharsets.UTF_8);
                        return decodedContent;

                    } else {
                        System.out.println("No content to decode");
                        return null;
                    }
                } else {
                    throw new RuntimeException("Failed to fetch data: " + response.message());
                }
            } catch (IOException e) {
                throw new RuntimeException("Error making HTTP request", e);
            }
        }
        else {
            System.err.println("This is not a file.");
            return "This is not a file.";
        }
    }

    /**
     * 显示文件内容。
     */

    public void showFileContent() {
        try {
            System.out.println(getFileInfo());
            System.out.println(getFileContent());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void showFileContents(Context context) {
        // 调用getFileContent()方法获取文件内容
        String fileContent = getFileContent(); // 假设这个方法从URL获取文件内容
        // 这里可以根据需要将文件内容显示在TextView、对话框等控件中
        // 例如，可以启动一个新的Activity来显示文件内容
        Intent intent = new Intent(context, GiteeFileContentActivity.class);
        intent.putExtra("fileContent", fileContent);
        context.startActivity(intent);
    }

    /**
     * 显示文件夹内容(所包含的文件)。
     *
     * @return
     */

    public List<GiteeFile> showDirContent() {
        if ("dir".equals(type)) {
            System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
            System.out.println("Dir: " + getName() + " " + getUrl());
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(url)
                    .header("Authorization", "token " + GiteeUser.accessToken)
                    .build();

            try (Response response = client.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    assert response.body() != null;
                    String responseBody = response.body().string();
                    Type listType = new TypeToken<List<GiteeFile>>() {
                    }.getType();
                    List<GiteeFile> contents = new com.google.gson.Gson().fromJson(responseBody, listType);

                    for (GiteeFile giteeFile : contents) {
                        giteeFile.showFileInfo();
                    }
                } else {
                    System.err.println("Failed to fetch repository contents: " + response.message());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("---------------------------------------------------------------------------------------");
        } else {
            System.err.println(this.name + " is not a directory.");
        }
        return null;
    }

    /**
     * 显示文件夹所有内容(递归调用所包含的文件和文件夹,仅供调试)。
     *
     * @return
     */

    public List<GiteeFile> showDirAllFiles() {
        List<GiteeFile> contents = null;
        if ("dir".equals(type)) {
            System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
            System.out.println("Dir: " + getName() + " " + getUrl());
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(url)
                    .header("Authorization", "token " + GiteeUser.accessToken)
                    .build();

            try (Response response = client.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    Type listType = new TypeToken<List<GiteeFile>>() {
                    }.getType();
                    contents = new com.google.gson.Gson().fromJson(responseBody, listType);

                    for (GiteeFile giteeFile : contents) {
                        giteeFile.showFileInfo();
                        if ("dir".equals(giteeFile.getType())) {
                            giteeFile.showDirAllFiles();
                        }
                    }
                } else {
                    System.err.println("Failed to fetch repository contents: " + response.message());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("---------------------------------------------------------------------------------------");
        }
        return contents;
    }


    /**
     * 获取
     *
     * @return type
     */
    public String getType() {
        return type;
    }

    /**
     * 设置
     *
     * @param type
     */
    public void setType(String type) {
        this.type = type;
    }

    /**
     * 获取
     *
     * @return size
     */
    public String getSize() {
        return size;
    }

    /**
     * 设置
     *
     * @param size
     */
    public void setSize(String size) {
        this.size = size;
    }

    /**
     * 获取
     *
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     *
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取
     *
     * @return path
     */
    public String getPath() {
        return path;
    }

    /**
     * 设置
     *
     * @param path
     */
    public void setPath(String path) {
        this.path = path;
    }

    /**
     * 获取
     *
     * @return sha
     */
    public String getSha() {
        return sha;
    }

    /**
     * 设置
     *
     * @param sha
     */
    public void setSha(String sha) {
        this.sha = sha;
    }

    /**
     * 获取
     *
     * @return url
     */
    public String getUrl() {
        return url;
    }

    /**
     * 设置
     *
     * @param url
     */
    public void setUrl(String url) {
        this.url = url;
    }

    /**
     * 获取
     *
     * @return html_url
     */
    public String getHtml_url() {
        return html_url;
    }

    /**
     * 设置
     *
     * @param html_url
     */
    public void setHtml_url(String html_url) {
        this.html_url = html_url;
    }

    /**
     * 获取
     *
     * @return download_url
     */
    public String getDownload_url() {
        return download_url;
    }

    /**
     * 设置
     *
     * @param download_url
     */
    public void setDownload_url(String download_url) {
        this.download_url = download_url;
    }

    /**
     * 获取
     *
     * @return _links
     */
    public _links get_links() {
        return _links;
    }

    /**
     * 设置
     *
     * @param _links
     */
    public void set_links(_links _links) {
        this._links = _links;
    }

    public String toString() {
        return "GiteeFile{type = " + type + ", size = " + size + ", name = " + name + ", path = " + path + ", sha = " + sha + ", url = " + url + ", html_url = " + html_url + ", download_url = " + download_url + ", _links = " + _links + "}";
    }


    public static class _links {
        private String self;
        private String html;

        public _links() {
        }

        public _links(String self, String html) {
            this.self = self;
            this.html = html;
        }

        public String getSelf() {
            return self;
        }

        public void setSelf(String self) {
            this.self = self;
        }

        public String getHtml() {
            return html;
        }

        public void setHtml(String html) {
            this.html = html;
        }

        public String toString() {
            return "_links{self = " + self + ", html = " + html + "}";
        }
    }
}
